//
//  Common.h
//  CityHunter
//
//  Updated by xcq on 2014-10-21.
//  Copyright (c) 2014年 CieNet. All rights reserved.
//
#import "JlUserManager.h"
#import "Common.h"
#import <CommonCrypto/CommonDigest.h>
#import <AFNetworking.h>
#import <objc/runtime.h>

#define TabBarRedPointWithMessage 0x321

@implementation Common

+ (ESystemVer)systemVersion {
    static ESystemVer SystemVer = 0;
    if (SystemVer == 0) {
        //判断系统版本
        if (CL_SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(@"6.0")) {
            SystemVer = ESystemVer6OrLess;
        } else if (CL_SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
            SystemVer = ESystemVer8OrGreater;
        } else {
            SystemVer = ESystemVer7;
        }
    }
    return SystemVer;
}

/*
 *{
     resultCount = 1;
     results =     (
         {
                artistId = 开发者 ID;
                artistName = 开发者名称;
                price = 0;
                isGameCenterEnabled = 0;
                kind = software;
                languageCodesISO2A =             (
                    EN
                );
                trackCensoredName = 审查名称;
                trackContentRating = 评级;
                trackId = 应用程序 ID;
                trackName = 应用程序名称";
                trackViewUrl = 应用程序介绍网址;
                userRatingCount = 用户评级;
                userRatingCountForCurrentVersion = 1;
                version = 版本号;
                wrapperType = software;
         }
     );
 }
 */

+ (UIImage *)imageWithImageSimple:(UIImage *)image
                     scaledToSize:(CGSize)newSize {
    
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageJPEGRepresentation(newImage,1.0);
    return newImage;
}

+ (void)getAppIcon {
    
}

+ (void)getUserInfo {
    
}


+ (void)checkVersionUpdate:(completion)callback {
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    CFShow((__bridge CFTypeRef)(infoDic));
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    
    NSString *URL = [NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",kAPPID];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:URL]];
    [request setHTTPMethod:@"POST"];

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue currentQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data,
                                               NSError *connectionError) {
                               
        if (data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                                options:NSJSONReadingMutableContainers
                                                                  error:NULL];
            NSDictionary *result = [[dic objectForKey:@"results"] firstObject];
            if (dic && [[dic objectForKey:@"resultCount"] boolValue] && result.allValues > 0) {
                NSString *version = [result objectForKey:@"version"];
                if ([currentVersion compare:version
                                    options:NSNumericSearch] == NSOrderedAscending) {
                    callback(YES,YES,NO,result);
                } else if ([currentVersion compare:version
                                           options:NSNumericSearch] == NSOrderedSame) {
                    callback(YES,NO,YES,[NSDictionary new]);
                } else {
                    callback(YES,NO,NO,[NSDictionary new]);
                }
            } else {
                callback(NO,NO,NO,[NSDictionary new]);
            }
        }
    }];
    
    
}

+ (BOOL)judgeAppInstall:(NSString *)urlStr{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlStr]] ;
}

+ (void)openThirdParty:(NSString *)urlStr{
    if ([self judgeAppInstall:urlStr]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }
}

+ (UIViewController*)viewController:(UIView *)view {
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

+ (void)callPhone:(NSString *)phone andControl:(UIView *)View{
    NSString *prefix = @"tel://";
    NSString *phoneNum = [prefix stringByAppendingString:phone];
    UIWebView *callPhoneWebVw = [[UIWebView alloc] init];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:phoneNum]];
    [callPhoneWebVw loadRequest:request];
    [View addSubview:callPhoneWebVw];
}

+ (CGSize)sizeWithContent:(NSString *)content AndFont:(UIFont *)font andSize:(CGSize)size  andLineBreak:(NSLineBreakMode)line {
    CGSize contentSize;
    if (!content ) {
        return CGSizeZero;
    }
    contentSize = [content sizeWithFont:font constrainedToSize:size lineBreakMode:line];
    return contentSize;
}

+ (void)setInputCustomerStyle:(UIView *)input {
    input.layer.cornerRadius = 6.0f;
    input.layer.masksToBounds = YES;
    input.layer.borderColor = BORDERCOLOR.CGColor;
    input.layer.borderWidth = 0.5f;
    if ([input isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField*)input;
        textField.textColor = TEXTCOLOR;
        //textField.font = CustomerFont(textField.font.pointSize);
    } else if ([input isKindOfClass:[UITextView class]]) {
        UITextView *textView = (UITextView*)input;
        textView.textColor = TEXTCOLOR;
        //textView.font = CustomerFont(textView.font.pointSize);
    }
}

#pragma mark - 计算单个文件大小
+ (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
  
    return 0;
}
#pragma mark 返回拉伸好的图片
+ (UIImage *)resizeImage:(NSString *)imgName {
    UIImage *image = [UIImage imageNamed:imgName];
    CGFloat leftCap = image.size.width * 0.5f;
    CGFloat topCap = image.size.height * 0.5f;
    // return [self resizableImageWithCapInsets:UIEdgeInsetsMake(topCap, leftCap, topCap - 1, leftCap - 1) resizingMode:UIImageResizingModeTile];
    return [image stretchableImageWithLeftCapWidth:leftCap topCapHeight:topCap];
    
}

+ (void)createRedPointToTabBar:(NSInteger)index {
    if ([[JlUserManager shareInstance].baseTab.tabBar viewWithTag:TabBarRedPointWithMessage]) {
        return;
    }
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = TabBarRedPointWithMessage;
    badgeView.backgroundColor = [UIColor redColor];
    CGRect tabFrame = [JlUserManager shareInstance].baseTab.tabBar.frame;
    
    //确定小红点的位置
    float percentX = (index + 0.6) / 5;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.1 * tabFrame.size.height);
    badgeView.frame = CGRectMake(x, y, 8, 8);
    badgeView.layer.cornerRadius = badgeView.frame.size.width/2;
    [[JlUserManager shareInstance].baseTab.tabBar addSubview:badgeView];
}

+ (void)removeRedPoint:(NSInteger)index {
    UIView *badgeView = [[JlUserManager shareInstance].baseTab.tabBar viewWithTag:TabBarRedPointWithMessage];
    if (badgeView) {
        [badgeView removeFromSuperview];
    }
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

#pragma mark - 遍历文件夹大小
+ (double) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [Common fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
+ (void)analyseNetworkResponseAndNotify:(id)rspData
                               moduleID:(NSInteger)moduleID
                              funIDSucc:(NSInteger)funIDSucc
                              funIDFail:(NSInteger)funIDFail {
    [Common analyseNetworkResponseAndNotify:(id)rspData
                                   moduleID:(NSInteger)moduleID
                                  funIDSucc:(NSInteger)funIDSucc
                                  funIDFail:(NSInteger)funIDFail
                                    success:nil
                                    failure:nil];
}
//
//+ (void)analyseNetworkResponseAndNotify:(id)rspData
//                               moduleID:(NSInteger)moduleID
//                              funIDSucc:(NSInteger)funIDSucc
//                              funIDFail:(NSInteger)funIDFail
//                                success:(void (^)(NSDictionary *dic))success
//                                failure:(void (^)(NSDictionary *dic))failure {
//    NSString *msg = nil;
//    if ([rspData isKindOfClass:[NSError class]]) {
//        [BF broadcastBusinessNotify:MakeID(moduleID, funIDFail) withInParam:rspData];
//    } else {
//        NSError *error = nil;
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:rspData
//                                                            options:NSJSONReadingMutableLeaves
//                                                              error:&error];
//        if (!error) {
//            LogDebug(@"response dic: %@", dic);
//            //若返回的是正确的数据包，则分析
//            NSString *resultCode = [dic objectForKey:NETWORK_RESPONSE_RETCODE_KEY];
//            msg = [dic objectForKey:NETWORK_RESPONSE_MESSAGE_KEY];
//            if (resultCode && resultCode.integerValue == NETWORK_RESPONSE_RETCODE_SUCC) {
//                if (success) {
//                    success(dic);
//                }
//                //返回成功，提前返回
//                [BF broadcastBusinessNotify:MakeID(moduleID, funIDSucc) withInParam:msg];
//                return;
//            } else {
//                if (failure) {
//                    failure(dic);
//                }
//                [BF broadcastBusinessNotify:MakeID(moduleID, funIDFail) withInParam:msg];
//            }
//        } else {
//            msg = error.localizedDescription;
//            [BF broadcastBusinessNotify:MakeID(moduleID, funIDFail) withInParam:msg];
//        }
//    }
//
//    //msg = NETWORK_RESPONSE_UNKNOWN_ERROR;
//    //[BF broadcastBusinessNotify:MakeID(moduleID, funIDFail) withInParam:msg];
//}
//
//+ (void)loginWithCurrentUser {
//    LogFunc;
//    NSString *currentUserName = [Common currentUserName];
//    NSString *currentPassword = [Common currentPassword];
//    NSArray *arr = [NSArray arrayWithObjects:currentUserName, currentPassword, nil];
//    [BF callBusinessProcess:MakeID(ELoginManager, ELoginLogin) withInParam:arr];
//}

+ (NSArray *)calDateIntervalFromEndDate:(NSString *)paramEndDate{
    if([paramEndDate isEqual:[NSNull null]] || paramEndDate == nil){
        return @[];
    }
    if ([paramEndDate isEqualToString:@""]) {
        return  @[];
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *startDate = [NSDate date];
    // NSDate *startDate = [formatter dateFromString:dateStr];
    NSDate *endData = [formatter dateFromString:paramEndDate];
    
    
    NSCalendar *chineseClendar = [ [ NSCalendar alloc ] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSUInteger unitFlags =  NSCalendarUnitHour | NSCalendarUnitMinute |NSCalendarUnitSecond | NSCalendarUnitDay| NSCalendarUnitMonth | NSCalendarUnitYear;
    //TO - FROM
    NSDateComponents *DateComponent = [chineseClendar components:unitFlags fromDate:endData toDate:startDate options:0];
    
    NSInteger diffHour = [DateComponent hour];
    
    NSInteger diffMin  = [DateComponent minute];
    
    NSInteger diffDay  = [DateComponent day];
    
    NSInteger diffMon  = [DateComponent month];
    
    NSInteger diffYear = [DateComponent year];
    return @[@(diffYear) , @(diffMon) , @(diffDay) , @(diffHour) , @(diffMin)];
//    if (diffYear>0) {
//        strResult=[NSString stringWithFormat:@"%ld",(long)diffYear];
//        strResult = [strResult stringByAppendingString:[Common getLocalStr:@"CLDateYearString"]];
//    }else if(diffMon>0){
//        strResult=[NSString stringWithFormat:@"%ld",(long)diffMon];
//        strResult = [strResult stringByAppendingString:[Common getLocalStr:@"CLDateMonthString"]];
//    }else if(diffDay>0){
//        strResult =[NSString stringWithFormat:@"%ld",(long)diffDay];
//        strResult = [strResult stringByAppendingString:[Common getLocalStr:@"CLDateDayString"]];
//    }else if(diffHour>0){
//        strResult=[NSString stringWithFormat:@"%ld",(long)diffHour];
//        strResult = [strResult stringByAppendingString:[Common getLocalStr:@"CLDateHourString"]];
//    }else if(diffMin>0){
//        strResult=[NSString stringWithFormat:@"%ld",(long)diffMin];
//        strResult = [strResult stringByAppendingString:[Common getLocalStr:@"CLDateMinuteString"]];
//    }else{
//        strResult = @"已结束";
//    }
//    return strResult;
}

+ (NSString*)getLocalStr:(NSString*)key {
    return key ? NSLocalizedStringFromTable(key, @"InfoPlist", nil) : key;
}

+ (void)showLocalAlert:(NSString*)title message:(NSString*)message {
    [Common showAlert:[Common getLocalStr:title]
              message:[Common getLocalStr:message]];
}

+ (void)showLocalAlert:(NSString *)title
               message:(NSString *)message
              delegate:(id<UIAlertViewDelegate>)delegate {
    [Common showAlert:[Common getLocalStr:title]
              message:[Common getLocalStr:message]
             delegate:delegate
             andAlert:0];
}

+ (void)showLocalAlert:(NSString*)localTitle message:(NSString*)localMessage andTag:(NSInteger)tag{
    [Common showAlert:[Common getLocalStr:localTitle]
              message:[Common getLocalStr:localMessage]
             delegate:nil
             andAlert:tag];
}

+ (void)showLocalAlert:(NSString *)localTitle
               message:(NSString *)localMessage
              delegate:(id<UIAlertViewDelegate>)delegate
                andTag:(NSInteger)tag{
    [Common showAlert:[Common getLocalStr:localTitle]
              message:[Common getLocalStr:localMessage]
             delegate:delegate andAlert:tag];
}

+ (void)showAlert:(NSString*)title message:(NSString*)message {
    [Common showAlert:title message:message delegate:nil andAlert:-1];
}


+ (void)showAlert:(NSString*)title message:(NSString *)message delegate:(id<UIAlertViewDelegate>)delegate andAlert:(NSInteger)tag{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:message
                                                   delegate:delegate
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:nil, nil];
    if (tag>0) {
        alert.tag = tag;
    }
    
    [alert show];
}

- (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName
{
    unsigned int outCount, i;
    // 获取对象里的属性列表
    objc_property_t * properties = class_copyPropertyList([instance
                                                           class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property =properties[i];
        //  属性名转成字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        // 判断该属性是否存在
        if ([propertyName isEqualToString:verifyPropertyName]) {
            free(properties);
            return YES;
        }
    }
    free(properties);
    return NO;
}

//+ (void)showJGActionSheet:(NSString *)title
//                  message:(NSString *)message
//              cancelTitle:(NSString*)cancelTitle
//             buttonTitles:(NSArray *)buttonTitles
//              buttonStyle:(JGActionSheetButtonStyle)buttonStyle
//                 delegate:(id<JGActionSheetDelegate>)delegate
//                      tag:(NSUInteger)tag
//               showInView:(UIView *)view {
//    JGActionSheetSection *section = [JGActionSheetSection sectionWithTitle:title
//                                                                   message:message
//                                                              buttonTitles:buttonTitles
//                                                               buttonStyle:buttonStyle];
//    
//    section.titleLabel.font = [UIFont systemFontOfSize:16.f];
//    section.titleLabel.textColor = [UIColor redColor];
//    
//    section.messageLabel.font = [UIFont systemFontOfSize:15.f];
//    section.messageLabel.textColor = [UIColor blackColor];
//    
//    for (UIButton *button in section.buttons) {
//        button.titleLabel.font = [UIFont systemFontOfSize:15.f];
//        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    }
//    
//    NSArray *sections = nil;
//    if (cancelTitle) {
//        JGActionSheetSection *cancelSection = [JGActionSheetSection sectionWithTitle:nil
//                                                                             message:nil
//                                                                        buttonTitles:@[cancelTitle]
//                                                                         buttonStyle:buttonStyle];
//        for (UIButton *button in cancelSection.buttons) {
//            button.titleLabel.font = [UIFont systemFontOfSize:15.f];
//            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        }
//        sections = @[section, cancelSection];
//    } else {
//        sections = @[section];
//    }
//    
//    JGActionSheet *actionSheet = [JGActionSheet actionSheetWithSections:sections];
//    actionSheet.tag = tag;
//    actionSheet.delegate = delegate;
//    
//    [actionSheet setButtonPressedBlock:^(JGActionSheet *actionSheet, NSIndexPath *indexPath) {
//        [actionSheet dismissAnimated:YES];
//    }];
//    
//    [actionSheet showInView:view animated:YES];
//}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


+ (int )returnRandom:(int)max {
    int ran = (arc4random() % max) + 1;
    return ran;
}


+ (void)setBaiDay {
    BOOL bol1 = [Common isBetweenFromHour:0 toHour:0];
    [[NSUserDefaults standardUserDefaults] setBool:bol1 forKey:UserKeyBaiDay];
}

+ (BOOL)isBaiDay {
    return [[NSUserDefaults standardUserDefaults] boolForKey:UserKeyBaiDay];
}

#pragma mark - 随机生成字符串
#define NUMBER_OF_CHARS 8
+ (NSString *)randomCreateNSString {
    char data[NUMBER_OF_CHARS];
    for (int x=0;x<NUMBER_OF_CHARS;data[x++] = (char)('a' + (arc4random_uniform(26))));
    return [[NSString alloc] initWithBytes:data length:NUMBER_OF_CHARS encoding:NSUTF8StringEncoding];
}

#define judge The Current Time
 /**
 * @brief 判断当前时间是否在fromHour和toHour之间。如，fromHour=8，toHour=23时，即为判断当前时间是否在8:00-23:00之间
 */
+ (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour
{
    NSDate *date8 = [Common getCustomDateWithHour:8];
    NSDate *date23 = [Common getCustomDateWithHour:18];
    
    NSDate *currentDate = [NSDate date];
    
    if ([currentDate compare:date8]==NSOrderedDescending && [currentDate compare:date23]==NSOrderedAscending)
    {
         return YES;
    }
    return NO;
}


/**
 * @brief 生成当天的某个点（返回的是伦敦时间，可直接与当前时间[NSDate date]比较）
 * @param hour 如hour为“8”，就是上午8:00（本地时间）
 */
+ (NSDate *)getCustomDateWithHour:(NSInteger)hour
{
    //获取当前时间
    NSDate *currentDate = [NSDate date];
    NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *currentComps = [[NSDateComponents alloc] init];
    
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    
    currentComps = [currentCalendar components:unitFlags fromDate:currentDate];
    
    //设置当天的某个点
    NSDateComponents *resultComps = [[NSDateComponents alloc] init];
    [resultComps setYear:[currentComps year]];
    [resultComps setMonth:[currentComps month]];
    [resultComps setDay:[currentComps day]];
    [resultComps setHour:hour];
    
    NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    return [resultCalendar dateFromComponents:resultComps];
}

#define KbaseUrl @"http://tapi.clejw.com/upheadimg.jsp"
+ (void)upLoadImage:(NSString *)kbaseUrl andFileSuffixRandom:(int)max andFile:(UIImage *)image andSucces:(void (^)(id))callback andFail:(void (^)(id))failCallback {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:kbaseUrl]];
    [request setHTTPMethod:@"POST"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy_MM_dd_HH_mm_ss"];
    NSString *fileName = [[[formatter stringFromDate:date] stringByAppendingString:[NSString stringWithFormat:@"%d",[self returnRandom:max]]] stringByAppendingPathExtension:@"png"];
     NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:[Common currentUserId] forKey:@"memberid"];
    [dic setObject:fileName forKey:@"content"];
    
    [manager POST:kbaseUrl parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        
        [formData appendPartWithFileData:data name:@"content" fileName:fileName
                                mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:NSJSONReadingMutableLeaves error:NULL];
        callback(dic);
 
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         failCallback(error);

     }];

}




#define MAX_FIT_SIZE_LENGTH   CGRectGetWidth([UIScreen mainScreen].bounds)
#define MAX_FIT_SIZE_HEIGHT   CGRectGetHeight([UIScreen mainScreen].bounds)

+ (CGSize)fitSizeForText:(NSString*)text font:(UIFont*)font {
    return [Common fitSizeForText:text font:font maxWidth:MAX_FIT_SIZE_LENGTH maxHight:MAX_FIT_SIZE_HEIGHT];
}

+ (CGSize)fitSizeForText:(NSString*)text font:(UIFont*)font maxWidth:(CGFloat)maxWidth {
    return [Common fitSizeForText:text font:font maxWidth:maxWidth maxHight:MAX_FIT_SIZE_HEIGHT];
}

+ (CGSize)fitSizeForText:(NSString*)text font:(UIFont*)font maxHight:(CGFloat)maxHeight {
    return [Common fitSizeForText:text font:font maxWidth:MAX_FIT_SIZE_LENGTH maxHight:maxHeight];
}

+ (CGSize)fitSizeForText:(NSString*)text font:(UIFont*)font maxWidth:(CGFloat)maxWidth maxHight:(CGFloat)maxHeight {
    //return [text sizeWithFont:font constrainedToSize:CGSizeMake(maxWidth,maxHeight) lineBreakMode:NSLineBreakByWordWrapping];
    return [text boundingRectWithSize:CGSizeMake(maxWidth,maxHeight)
                              options:NSStringDrawingUsesLineFragmentOrigin
                           attributes:@{NSFontAttributeName:font}
                              context:nil].size;
}

+ (void)printFrame:(CGRect)frame message:(NSString*)msg {
    NSLog(@"%@, originX: %f, originY: %f, width: %f, height: %f", msg, frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
}

+ (BOOL)isEmptyString:(NSString*)string {
    if (string) {
        NSString *str = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if (![str isEqualToString:@""]) {
            return NO;
        }
    }
    
    return YES;
}

+ (NSString *) md5:(NSString*)string {
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), digest );
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02X", digest[i]];
    
    return output;
}

+ (void)setLoginStatus:(BOOL)bol{
    [[NSUserDefaults standardUserDefaults]setBool:bol forKey:UserkeyLoginStatus];
    
}

+ (BOOL)currenLoginStatus{
    return [[[NSUserDefaults standardUserDefaults] objectForKey:UserkeyLoginStatus] boolValue];
}

+ (NSNumber *)currenVB{
    return [[NSUserDefaults standardUserDefaults]objectForKey:UserKeyCurrentVB];
}

+ (void)setUserInfo:(NSDictionary *)dic{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
    [Common setUserId:[dic customObjectForkey:@"ID"]];
    [Common setPhoneNum:[dic customObjectForkey:@"MOBILE"]];
    [Common setCurrenVB:@([[dic customObjectForkey:@"VB"] integerValue])];
    [Common setCurrenUserName:[dic customObjectForkey:@"NAME"]];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:UserKeyCurrentUserInfo];
}

+ (void)setUserName:(NSString *)name {
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:UserKeyCurrentUserZh];
}

+ (NSString *)userName {
    return  [[NSUserDefaults standardUserDefaults] stringForKey:UserKeyCurrentUserZh];
}

+ (void)setAutoLogin:(BOOL)bol {
    [[NSUserDefaults standardUserDefaults]setBool:bol forKey:UserKeyAutoLogin];
}

+ (BOOL)currenAutoLogin {
    return  [[NSUserDefaults standardUserDefaults] boolForKey:UserKeyAutoLogin];
}

+ (void)setCurrenVB:(NSNumber *)vb{
    [[NSUserDefaults standardUserDefaults] setObject:vb forKey:UserKeyCurrentVB];
}

+ (void)setToken:(NSString *)token{
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:UserKeyCurrentToken];
}

+ (void)setCurrenUserName:(NSString *)name{
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:UserKeyCurrentUserName];
}

+ (void)setPassWord:(NSString *)password{
    [[NSUserDefaults standardUserDefaults] setObject:password forKey:UserKeyCurrentPassword];
}

+ (void)setUserId:(NSString *)userId{
    [[NSUserDefaults standardUserDefaults] setObject:userId forKey:UserkeyCurrentUserId];
}

+ (void)setPhoneNum:(NSString *)PhoneNum{
    [[NSUserDefaults standardUserDefaults] setObject:PhoneNum forKey:UserKeyCurrentPhoneNum];
    
}

+ (void)setCurrenCity:(NSMutableDictionary *)city{
    [[NSUserDefaults standardUserDefaults] setObject:city forKey:UserKeyCurrentAddress];
}

+ (void)setCurrenPhoto:(NSString *)photoData{
    [[NSUserDefaults standardUserDefaults] setObject:photoData forKey:UserKeyCurrentPhoto];
}

+ (NSString *)currenPhoto{
    return [[NSUserDefaults standardUserDefaults] objectForKey:UserKeyCurrentPhoto];
}

+ (NSString*)currentToken {
    return [[NSUserDefaults standardUserDefaults] objectForKey:UserKeyCurrentToken];
}

+ (NSDictionary*)currentUserInfo {
    NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:UserKeyCurrentUserInfo]];
    return dic;
}

+ (NSMutableDictionary *)currenCity{
    return [[NSUserDefaults standardUserDefaults] objectForKey:UserKeyCurrentAddress];
}

+ (NSString*)currentUserName {
    //    return @"abc";
    return [[NSUserDefaults standardUserDefaults] objectForKey:UserKeyCurrentUserName];
}

+ (NSString*)currentPassword {
    return [[NSUserDefaults standardUserDefaults] objectForKey:UserKeyCurrentPassword];
}

+ (NSString *)currentUserId{
    //    return @"123";
    return [[NSUserDefaults standardUserDefaults] objectForKey:UserkeyCurrentUserId];
}

+ (NSString*)currentPhoneNum {
    return [[NSUserDefaults standardUserDefaults] objectForKey:UserKeyCurrentPhoneNum];
}

+ (BOOL)regexString:(NSString*)string match:(NSString*)match {
    NSPredicate *regex = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", match];
    if ([regex evaluateWithObject:string]) {
        return YES;
    }
    
    return NO;
}

+ (BOOL)isMobileNumber:(NSString *)string
{
    
    //     * 手机号码
    //     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
    //     * 联通：130,131,132,152,155,156,185,186
    //     * 电信：133,1349,153,180,189
    //     */
    //    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\\\d{8}$";
    //    /**
    //     10         * 中国移动：China Mobile
    //     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
    //     12         */
    //    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\\\d)\\\\d{7}$";
    //    /**
    //     15         * 中国联通：China Unicom
    //     16         * 130,131,132,152,155,156,185,186
    //     17         */
    //    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\\\d{8}$";
    //    /**
    //     20         * 中国电信：China Telecom
    //     21         * 133,1349,153,180,189
    //     22         */
    //    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\\\d{7}$";
    //    /**
    //     25         * 大陆地区固话及小灵通
    //     26         * 区号：010,020,021,022,023,024,025,027,028,029
    //     27         * 号码：七位或八位
    //     28         */
    //    // NSString * PHS = @"^0(10|2[0-5789]|\\\\d{3})\\\\d{7,8}$";
    //
    //    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    //    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    //    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    //    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    //
    //    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
    //        || ([regextestcm evaluateWithObject:mobileNum] == YES)
    //        || ([regextestct evaluateWithObject:mobileNum] == YES)
    //        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    //    {
    //        return YES;
    //    }
    //    else
    //    {
    //        return NO;
    //    }
    return [Common regexString:string match:@"^1[0-9]{10}$"];
}

+ (BOOL)isNumAndLetter:(NSString *)string {
    return [Common regexString:string match:@"/[^\d|chun]/g,'"];
}

+ (BOOL)isUserName:(NSString*)string {
    return [Common regexString:string match:@"^\\w{6,16}$"];
}

+ (BOOL)isPassword:(NSString*)string {
    return [Common regexString:string match:@"^\\w{4,14}$"];
}

+ (BOOL)isRealName:(NSString*)string {
    return [Common regexString:string match:@"^[\\u4e00-\\u9fa5A-Za-z0-9_]{4,20}$"];
}

+(BOOL)isValidateEmail:(NSString *)string {
    
    return [Common regexString:string match:@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"];
    
}

+ (NSDate *)getLocalDateFormateUTCDate:(NSDate *)anyDate
{
    //设置源日期时区
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    //设置转换后的目标日期时区
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
    
    return destinationDateNow;
}

//+ (BOOL)isSystemUserName:(NSString*)str{
//    return [Common regexString:str match:@"/[(' ')('`')(\~)('!')(\@)(\#)('$')(\%)('^')(\&)(\*)(\()('\'))(\+)('=')(\|)(\{)(\})(\')(':')(';')(\')(',)(\[)(']')('.')('<')('>')('/')(\?)(\~)(\！)(\@)(\#)(\￥)(\%)(\…)(\&)(\*)(\（)(\）)(\—)(\+)(\|)(\{)(\})(\【)(\】)(\‘)(\；)(\：)(\”)(\“)(\’)(\。)(\，)(\、)(\？)]+/"];
//}

+ (BOOL)verificationNickName:(NSString *)nickName {
    if ([@"" isEqualToString:nickName]) {
        return YES;
    }
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", kChinese];
    NSPredicate *englishPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", kEnglish];
    return  [predicate evaluateWithObject:nickName] || [englishPre evaluateWithObject:nickName];
}

+ (BOOL)isIDNumber:(NSString*)string {
    return [Common regexString:string match:@"^[0-9Xx]{15}$"] || [Common regexString:string match:@"^[0-9Xx]{18}$"];
}

+ (NSMutableDictionary *)loadPlist:(NSString *)plistName {
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath = [paths objectAtIndex:0];
    //得到完整的文件名
    NSString *filename=[[plistPath stringByAppendingPathComponent:plistName] stringByAppendingPathExtension:@"plist"];    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:filename];
    return data;
}

+ (BOOL)writePlist:(NSMutableDictionary *)dic plistName:(NSString *)plist{
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath = [paths objectAtIndex:0];
    //得到完整的文件名
    NSString *filename=[[plistPath stringByAppendingPathComponent:plist] stringByAppendingPathExtension:@"plist"];
    return  [dic writeToFile:filename atomically:YES];
}

//根据输入的参数，转换成url的参数字符串
+ (NSString*)URLEncodedStringFromKeyAndValue:(NSString*)key value:(id)value {
    NSMutableArray *mutablePairs = [NSMutableArray array];
    for (NSDictionary *dic in [Common queryStringPairsFromKeyAndValue:key value:value]) {
        id fieldInPair = [dic objectForKey:@"field"];
        id valueInPair = [dic objectForKey:@"value"];
        if (valueInPair && ![valueInPair isEqual:[NSNull null]]) {
            NSString *fieldEncoding = (__bridge_transfer  NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)fieldInPair, (__bridge CFStringRef) @"[].", (__bridge CFStringRef)@":/?&=;+!@#$()',*", CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
            NSString *valueEncoding = (__bridge_transfer  NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)valueInPair, (__bridge CFStringRef) @"[].", (__bridge CFStringRef)@":/?&=;+!@#$()',*", CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
            
            [mutablePairs addObject:[NSString stringWithFormat:@"%@=%@", fieldEncoding, valueEncoding]];
        }
    }
    
    return [mutablePairs componentsJoinedByString:@"&"];
}

//将字典的参数转换成字符串的数组，用以在post请求的url中
+ (NSArray*)queryStringPairsFromKeyAndValue:(NSString*)key value:(id)value {
    NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
    
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description"
                                                                     ascending:YES
                                                                      selector:@selector(compare:)];
    if ([value isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dictionary = value;
        // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
        for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
            id nestedValue = [dictionary objectForKey:nestedKey];
            if (nestedValue) {
                [mutableQueryStringComponents addObjectsFromArray:[Common queryStringPairsFromKeyAndValue:(key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey) value:nestedValue]];
            }
        }
    } else if ([value isKindOfClass:[NSArray class]]) {
        NSArray *array = value;
        for (id nestedValue in array) {
            [mutableQueryStringComponents addObjectsFromArray:[Common queryStringPairsFromKeyAndValue:[NSString stringWithFormat:@"%@[]", key] value:nestedValue]];
        }
    } else if ([value isKindOfClass:[NSSet class]]) {
        NSSet *set = value;
        for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
            [mutableQueryStringComponents addObjectsFromArray:[Common queryStringPairsFromKeyAndValue:key value:obj]];
        }
    } else {
        [mutableQueryStringComponents addObject:[NSDictionary dictionaryWithObjectsAndKeys:value, @"value", key, @"field", nil]];
    }
    
    return mutableQueryStringComponents;
}

+ (BOOL)copyResourceToDocumentsFolder:(NSString*)fileName {
    NSString *name = [fileName stringByDeletingPathExtension];
    NSString *ext = [fileName pathExtension];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:name ofType:ext];
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:filePath]) {
        BOOL isDir = NO;
        if ([fm fileExistsAtPath:ResourceDirectory isDirectory:&isDir]) {
            if (!isDir) {
                //删除已有同名的文件
                if (isDir && ![fm removeItemAtPath:ResourceDirectory error:nil]) {
                    NSLog(@"delete file fail: %@", ResourceDirectory);
                    return NO;
                }
                //重新创建文件夹
                if (![fm createDirectoryAtPath:ResourceDirectory withIntermediateDirectories:YES attributes:nil error:nil]) {
                    NSLog(@"create directory fail: %@", ResourceDirectory);
                    return NO;
                }
            }
        } else {
            //创建文件夹
            if (![fm createDirectoryAtPath:ResourceDirectory withIntermediateDirectories:YES attributes:nil error:nil]) {
                NSLog(@"create directory fail: %@", ResourceDirectory);
                return NO;
            }
        }
        
        //目标文件路径
        NSString *desFilePath = [ResourceDirectory stringByAppendingPathComponent:fileName];
        if ([fm fileExistsAtPath:desFilePath]) {
            //若存在，先删除
            NSError *error = nil;
            if (![fm removeItemAtPath:desFilePath error:&error]) {
                NSLog(@"move file fail: %@, error: %@", desFilePath, error.description);
                return NO;
            }
        }
        
        //转移文件到外层，便于查看
        NSError *error = nil;
        if (![fm copyItemAtPath:filePath toPath:desFilePath error:&error]) {
            NSLog(@"move file fail: %@, error: %@", filePath, error.description);
            return NO;
        }
    }
    
    return YES;
}

+ (NSString*)getResourceFilePath:(NSString*)fileName {
    if ([Common copyResourceToDocumentsFolder:fileName]) {
        return [ResourceDirectory stringByAppendingPathComponent:fileName];
    }
    
    return nil;
}

+ (NSString*)getErrorDescription:(NSString*)errorCode
{
    if ([errorCode isEqualToString:@"30002"])
    {
        //        [[NSUserDefaults standardUserDefaults] removeObjectForKey:UserKeyCurrentToken];
    }
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ServerErrorMessage" ofType:@"plist"];
    NSDictionary *promptMsgDict = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *errorMsg = [promptMsgDict objectForKey:errorCode];
    if (errorMsg == nil || [errorMsg isEqualToString:@""])
    {
        return @"系统繁忙，请稍后重试";
    }
    return errorMsg;
}


+ (BOOL)isNetWorkReachable:(void (^)(NSInteger status))block{
    AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [afNetworkReachabilityManager startMonitoring];  //开启网络监视器；
    
    //    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(afNetworkStatusChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
    [afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:{
                [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:CURRENNETWORKINGSTATUS];
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:{
                [[NSUserDefaults standardUserDefaults] setObject:@"2" forKey:CURRENNETWORKINGSTATUS];
                
                //rect.origin.y = footView.frame.origin.y + footView.frame.size.height;
                //PPRSLog(@"网络通过WIFI连接：%f", rect.origin.y );
                break;
            }                
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:CURRENNETWORKINGSTATUS];
                //rect.origin.y = footView.frame.origin.y + footView.frame.size.height;
                //PPRSLog(@"网络通过无线连接：%f", rect.origin.y );
                break;
            }
            default:
                [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:CURRENNETWORKINGSTATUS];
                
                break;
        }
        
        if (block) {
            block(status);
        }
        [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
        //_nonNetworkLabel.frame = rect;
        //PPRSLog(@"网络状态数字返回：%i", status)
        //PPRSLog(@"网络状态返回: %@", AFStringFromNetworkReachabilityStatus(status));
    }];
    
    return YES;
}
 

@end
